package com.joeyzh.table;

import android.graphics.Color;
import android.support.annotation.LayoutRes;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.joey.base.util.LogUtils;
import com.joey.base.util.ResourcesUtils;
import com.joey.ui.CheckedModel;
import com.joey.ui.adapter.CheckedAdapter;
import com.joey.ui.widget.ToastHelper;
import com.joeyzh.R;
import com.joeyzh.base.ItemViewModel;
import com.joeyzh.utils.CheckedModelFilter;
import com.joeyzh.utils.DateFormatConsts;
import com.joeyzh.utils.ModelFilter;
import com.joeyzh.utils.TypeConsts;
import com.joeyzh.widget.MyDatePicker;
import com.joeyzh.widget.PopUpSpinner;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Joey on 2018/12/27.
 *
 * @author by Joey
 *         自定义Table样式，用于还原日志业务的书写
 */

public class BaseTableViewModel extends ItemViewModel<TableLogEntity> implements LogViewModelItemDelegate {

    /**
     * 所有下拉控件
     */
    private TableLayout parent;
    /**
     * 下拉数据
     */
    private HashMap<String, TableLogItemEntity> dictsCodeMap = new HashMap<>();

    public BaseTableViewModel(TableLayout parent, TableLogEntity entity) {
        super(entity);
        this.parent = parent;
        dictsCodeMap = new HashMap<>();
    }

    public List<TableLogItemEntity> getImageItems() {
        return getEntityBean().getImageValues();
    }

    public List<TableLogItemEntity> getcustomItems() {
        return getEntityBean().getCustomValues();
    }

    public List<TableLogItemEntity> getMutiItems() {
        return getEntityBean().getMutiValues();
    }

    public HashMap<String, TableLogItemEntity> getDictItems() {
        return dictsCodeMap;
    }

    /**
     * 更新整个表单
     *
     * @param entity
     */
    @Override
    public void updateEntityBean(TableLogEntity entity) {
        super.updateEntityBean(entity);
        bindAllViews();

    }

    /**
     * 遍历绑定所有组件数据
     */
    public void bindAllViews() {
        List<TableLogItemEntity> items = getEntityBean().getParamValues();
        if (items == null || items.isEmpty()) {
            return;
        }
        getImageItems().clear();
        getcustomItems().clear();
        dictsCodeMap.clear();
        getDictItems().clear();
        getMutiItems().clear();
        getEntityBean().getItemEntityHashMap().clear();
        int i = 0;
        for (TableLogItemEntity item : items) {
            /**
             *             如果某一条数据出现问题，就抛出一个异常
             */
            try {
                if (TextUtils.isEmpty(item.getParamCode())) {
                    item.setParamCode(item.getType() + i);
                }
                getEntityBean().getItemEntityHashMap().put(item.getParamCode(), item);
                item.parseConfig();
                createTableItem(parent, item);
            } catch (Exception e) {
                e.printStackTrace();
                LogUtils.e(item.getParamCode());
            }
            i++;
        }
    }

    /**
     * 绑定某项表单
     *
     * @param parent
     * @param entity
     */
    @Override
    public void createTableItem(TableLayout parent, TableLogItemEntity entity) throws Exception {
        ViewGroup itemGroupView = (ViewGroup) View.inflate(parent.getContext(), getLayoutRes(entity), null);
        parent.addView(itemGroupView, TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
        bindViewItem(entity.getParamCode(), itemGroupView);
        /**
         * 设置表头标签
         */
        bindTagView(entity);

        /**
         * 调整布局样式
         */
        setLayoutParams(entity, itemGroupView);
        /**
         * 设置Value的样式
         */
        bindParamView(entity);

    }

    /**
     * 设置标签文本
     *
     * @param entity
     */
    public void bindTagView(TableLogItemEntity entity) {
        TextView tvTag = getParamTagView(entity);
        if (tvTag != null) {
            tvTag.setTag(entity);
            //是否必填  必填
            int requiredLength = 0;
            String text = entity.getText();
            if (TextUtils.isEmpty(entity.isRequired())) {
                text = "* " + entity.getText();
                requiredLength = "* ".length();
            }
            SpannableString spannableString = new SpannableString(text);
            // 如果存在重点强调的内容
            if (!TextUtils.isEmpty(entity.getUnderLine())) {
                String texts[] = text.split(TableLogItemEntity.SPIT);
                String underlines[] = entity.getUnderLine().split(",");
                for (int i = 0; i < underlines.length; i++) {
                    text = text.replace(TableLogItemEntity.SPIT, underlines[i]);
                }
                spannableString = new SpannableString(text);
                for (int i = 0; i < texts.length - 1; i++) {
                    int start = texts[i].length();
                    int end = start + underlines[i].length();
                    spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableString.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableString.setSpan(new UnderlineSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
            spannableString.setSpan(new ForegroundColorSpan(Color.RED), 0, requiredLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            tvTag.setText(spannableString);
        }
    }

    /**
     * 设置数据绑定内容
     *
     * @param entity
     */
    public boolean bindParamView(final TableLogItemEntity entity) throws Exception {
        final ViewGroup itemGroupView = getView(entity.getParamCode());
        if (itemGroupView == null) {
            return false;
        }
        if (getEntityBean().isEditable()) {
            itemGroupView.setEnabled(entity.isEnable());
        } else {
            itemGroupView.setEnabled(getEntityBean().isEditable());
        }
        final View tvValue = getParamValueView(entity);
        if (tvValue == null) {
            return false;
        }
        tvValue.setTag(entity);
        if (tvValue instanceof TextView) {
            ((TextView) tvValue).setText(entity.getParamValue());
        }
        String type = entity.getType();
        switch (ComponentType.valueOf(type)) {
            case Custom:
                tvValue.setId(ResourcesUtils.getId(String.format("fl_custom_content_%d", getcustomItems().size() - 1)));
                return true;
            case Description:
                ((LinearLayout) itemGroupView).setOrientation(LinearLayout.VERTICAL);
                ((TextView) tvValue).setText(entity.getConfigEntry().get("DescriptionMessage").toString());
                return true;
            case Text:
                ((TextView) tvValue).setText(entity.getParamValue());
                return true;
            case InputMore:
            case InputSingle:
                setText(((TextView) tvValue), entity.getParamValue());
                ((TextView) tvValue).setHint(entity.getConfigEntry().get("Text").toString());
                return true;
            case Button:
                ((Button) tvValue).setText(entity.getText());
                return true;
            case Date:
                /**
                 * 日期样式
                 */
                ((MyDatePicker) tvValue).setType(MyDatePicker.TYPE_DATE);
            case Time:
                if (!TextUtils.isEmpty(entity.getParamValue()) && entity.getParamValue().endsWith("Z")) {
                    Date date = DateFormatConsts.convertStrToDate(entity.getParamValue(), DateFormatConsts.FORMATTER_DATE_AND_TIME_TZ);
                    ((MyDatePicker) tvValue).setCurrentTime(date);
                } else {
                    ((MyDatePicker) tvValue).setCurrentTime(new Date());
                }
                return true;
            case Image:
                /**
                 * 图片样式
                 */
                tvValue.setId(ResourcesUtils.getId(String.format("fl_image_content_%d", getImageItems().size() - 1)));
                return true;
            case Number:
                /**
                 * 数字输入
                 */
                ((EditText) tvValue).setInputType(EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_FLAG_DECIMAL);
                if (entity.getConfigEntry().containsKey("MinValue") && entity.getConfigEntry().containsKey("MaxValue")) {
                    ((EditText) tvValue).setHint(String.format("数值介于在（%s~%s之间）", entity.getConfigEntry().get("MinValue").toString(), entity.getConfigEntry().get("MaxValue").toString()));
                } else if (entity.getConfigEntry().containsKey("MinValue")) {
                    ((EditText) tvValue).setHint("最小值不能小于" + entity.getConfigEntry().get("MinValue").toString());
                } else if (entity.getConfigEntry().containsKey("MaxValue")) {
                    ((EditText) tvValue).setHint("最大值不能大于" + entity.getConfigEntry().get("MaxValue"));
                }
                return true;
            /**
             * 选择样式
             */
            case Checked:
                ((TextView) tvValue).setText("");
                try {
                    boolean isChecked = Boolean.parseBoolean(entity.getParamValue());
                    ((CheckBox) tvValue).setChecked(isChecked);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                itemGroupView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ((CheckBox) tvValue).toggle();
                    }
                });
                return true;
            /**
             * 下拉样式
             */
            case Selected:
            case SelectedMulti:
                final List<? extends CheckedModel> temp = entity.getItems();
                ((PopUpSpinner) tvValue).setAdapter(temp, R.layout.item_check_simple_center_popup, CheckedAdapter.TYPE_MULTI_SELECTED);
                if (ComponentType.Selected.toString().equals(entity.getType())) {
                    ((PopUpSpinner) tvValue).setAdapter(temp, R.layout.item_check_simple_center_popup);
                }
                ((PopUpSpinner) tvValue).setCode(entity.getParamCode());
                ((PopUpSpinner) tvValue).setSelectedbyIds(entity.getParamValue());
                ((PopUpSpinner) tvValue).notifyDataSetChanged();
                ((PopUpSpinner) tvValue).setText(entity.getParamValue());
                break;
            default:
                break;
        }

        return true;
    }

    /**
     * 获取Tag视图
     *
     * @param entity
     * @return
     */
    @Override
    public TextView getParamTagView(TableLogItemEntity entity) {
        View parent = getView(entity.getParamCode());
        if (parent == null) {
            return null;
        } else {
            return parent.findViewById(R.id.tv_tag_name);
        }
    }

    @Override
    public <T extends View> T getParamValueView(TableLogItemEntity entity) {
        return getParamValueView(entity.getParamCode());
    }

    public <T extends View> T getParamValueView(String paramCode) {
        View parent = getView(paramCode);
        if (parent == null) {
            return null;
        } else {
            return parent.findViewById(R.id.tv_value);
        }
    }

    @Override
    public void bindBeanValues() {
        List<TableLogItemEntity> items = getEntityBean().getParamValues();
        if (items == null || items.isEmpty()) {
            return;
        }
        /**
         * 遍历子项目挨个赋值
         */
        for (int i = 0; i < items.size(); i++) {
            TableLogItemEntity item = items.get(i);
            /**
             * 错误数据
             */
            if (null == item.getType() || TextUtils.isEmpty(item.getParamCode())) {
                items.remove(i--);
                continue;
            }

            /**
             * 分割线，纯文本类型等不在组织的范围中
             */
            switch (ComponentType.valueOf(item.getType())) {
                case MidView:
                case MinView:
                case Custom:
                case Image:
                case Button:
                case SelectedMulti:
                    items.remove(i--);
                    continue;
                default:
            }
            /**
             *  将子视图数据取出来
             */
            View valueView = getParamValueView(item);
            if (valueView == null) {
                continue;
            }
            /**
             * 单选样式的，直接设置Value
             */
            if (valueView instanceof CheckBox) {
                //结果  是/否
                item.setParamValue(((CheckBox) valueView).isChecked() ? TypeConsts.YES : TypeConsts.NO);
                continue;
            }
            if (valueView instanceof MyDatePicker) {
                MyDatePicker picker = getParamValueView(item);
                item.setParamValue(DateFormatConsts.getTime(picker.getActualDate().getTime(), DateFormatConsts.FORMATTER_DATE_AND_TIME_TZ));
                continue;
            }
            if (valueView instanceof TextView) {
                // value 为空直接不传value
                String text = ((TextView) valueView).getText().toString().trim();
                item.setParamValue(TextUtils.isEmpty(text) ? null : text);
                continue;
            }
            if (valueView instanceof PopUpSpinner) {
                String id = ((PopUpSpinner) valueView).getSelectedIds();
                if (PopUpSpinner.IDEA_ID.equals(id) || TextUtils.isEmpty(id)) {
                    item.setParamValue(null);
                } else {
                    item.setParamValue(id);
                }
                continue;
            }
        }

    }

    private void setLayoutParams(TableLogItemEntity entity, ViewGroup item) {
        if (item instanceof LinearLayout) {
            //存在两项   长度大于8
            if (item.getChildCount() > 1 && entity.getText().length() > 8) {
                View view = item.getChildAt(1);
                if (view instanceof EditText || view instanceof PopUpSpinner) {
                    ((LinearLayout) item).setOrientation(LinearLayout.VERTICAL);
                    //修改样式
                    ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
                    layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
                    view.setLayoutParams(layoutParams);
                    LogUtils.e("entity text = " + entity.getText() + " 设置布局格式");
                }
            }
        }
    }

    @LayoutRes
    private int getLayoutRes(TableLogItemEntity item) {

        ComponentType type = ComponentType.valueOf(item.getType());
        switch (type) {
            case Checked:
                return R.layout.include_tb_item_checked;
            case Description:
            case Text:
                return R.layout.include_tb_item_text;
            case Number:
            case InputSingle:
                return R.layout.include_tb_item_input_single;
            case InputMore:
                return R.layout.include_tb_item_input_more;
            case Selected:
            case SelectedMulti:
                dictsCodeMap.put(item.getParamCode(), item);
                if (type == ComponentType.SelectedMulti) {
                    getMutiItems().add(item);
                }
                return R.layout.include_tb_item_spinner;
            case Time:
            case Date:
                return R.layout.include_tb_item_date;
            case Image:
                getImageItems().add(item);
                return R.layout.include_tb_item_image;
            case MinView:
                return R.layout.include_tb_item_min_view;
            case MidView:
                return R.layout.include_tb_item_mid_view;
            case ScanEdit:
                return R.layout.include_tb_item_scan_edit;
            case Button:
                return R.layout.include_tb_item_btn;
            default:
                getcustomItems().add(item);
                return R.layout.include_tb_item_image;
        }

    }

    public List<TableLogItemEntity> getValues() {
        return getEntityBean().getParamValues();
    }
}
